//box实时获取数据并显示到页面
//传参:paraid,startime,endtime;获取一定时间段的数据
// $(function () {
//      $('#sensor_group').change(function () {
//          //alert($(this).children('option:selected').val());
//      })
//  })
function releaseWarning(EarlyWarningId){
    //alert(EarlyWarningId);
    //解除预警js
    $.ajax(
        {
            url: "/bridge/releasewarning",
            type: "POST",
            dataType: "json",
            data: {earlywarnigid: EarlyWarningId},
            success: function (result) {
                if(result == 1)
                {
                    alert("预警解除成功");
                }
            }
        });

}
$(function () {
    getRealTimeData("box","0000000236f100ff0000000000d30005","测试");//第一次获取
    // setInterval(function () {
    //     getRealTimeData();
    // },1000);//两秒钟获取一次数据
})
function showdata(paraId,cdName){
    //加div显示实时数据
    showdatadiv = "<div class='col-md-6'><div class='card'><div class='card-header'><div class='text-md-center'><p class='card-title'>" + cdName
    + "</p></div></div><div class='card-body'><div id='box"+paraId+"' style='width: 100%; height:300px;'></div></div></div></div>".replace(/[\r\n]/g,"");
    $("#realtimeData").append(showdatadiv);
    getRealTimeData("box"+paraId, paraId,cdName);
}
//获取实时数据函数
function getRealTimeData(datadom,paraId,cdName){
    //初始化box
    var dom = document.getElementById(datadom);
    var myChart = echarts.init(dom);
    var app = {};
    option = null;
    //获取或者传值获取ParaID
    var paraid = paraId;//先取默认值，后期需要改变值
    //获取当前时间，因为数据原因，先去固定时间段
    //var base = + new Date(2019,2,1,9,12,05);//设置开始时间，默认为当前时间前10秒
    var base = + new Date();
    //定义一些变量如1分钟
    var oneminute = 1000 ;// 一分钟等于多少毫秒，后期改成一秒
    var startime =new Date(base - oneminute * 70);
    var endtime = new Date(base - oneminute * 60);//第一次请求10秒钟的数据,后面每一秒钟请求一次
    //初始化时间和数据初始化数组
    console.log(startime);
    console.log(endtime);
    var date = [];
    var data = [];
    var AllDetailData =[];
    var paraType = "";
    //Ajax通过ParaID获取阈值
    var firstThreshold = 0;
    var secondThreshold = 0;
    var maxWarning = 0;
    var FirstWarningCount = 0;
    var SecondWarningCount = 0;
    //获取最大异常数据数量
    $.ajaxSettings.async = false;//设置ajax同步提交
    $.getJSON("/setting/getAllWarningSetting",function (MaxWarningresult) {
        $.each(MaxWarningresult,function (i,item) {
            console.log(item["thresholdNum"]);
            maxWarning=item["thresholdNum"];
        })
    })
    //获取一级二级阈值
    $.ajax(
        {
            url:"/setting/getThresholdBySensorID",
            type:"POST",
            dataType:"json",
            async:false,
            data:{SID:paraId},
            success:function (result) {
                //console.log(result["firstThreshold"]);
                //console.log(result["secondThreshold"]);
                firstThreshold = result["firstThreshold"];
                secondThreshold = result["secondThreshold"];
            },
            error: function (xhr, status, p3, p4) {
                var err = "Error " + " " + status + " " + p3;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).message;
                console.log(err);
                //说明未获取到阈值
                alert("该传感器未设置阈值，请设置阈值，点击确定前往");
                window.location.href = "/setting/threshold";
            }
        });
    //定义内部函数
    function addData(shift){
        //先请求数据并添加
       
        startime = [startime.getFullYear(),startime.getMonth()+1,startime.getDate()].join("/")+" "+[startime.getHours(),startime.getMinutes(),startime.getSeconds()].join(":");

        endtime = [endtime.getFullYear(),endtime.getMonth()+1,endtime.getDate()].join("/")+" "+[endtime.getHours(),endtime.getMinutes(),endtime.getSeconds()].join(":");
        console.log(startime);
        console.log(endtime);
        //开始请求数据并加入到数据中
         $.ajax(
        {
            url:"/bridge/realtimesensordata",
            type:"POST",
            dataType:"json",
            async:false,
            data:{paraid:paraid,starttime:startime,endtime:endtime},
            success:function (result) {
                //console.log(result);
                $.each(result,function (i,item) {
                    //将数据添添加到数组中去
                    date.push(item["collectTime"]);
                    data.push(item["paraValue"]);
                    AllDetailData[item["collectTime"]]=item;//以时间来存储对象
                    paraType = item["paraTypeCode"];
                });
            },
            error: function (xhr, status, p3, p4) {
                var err = "Error " + " " + status + " " + p3;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).message;
                console.log(err);
            }
        });

        if (shift) {
            date.shift();
            data.shift();
        }//判断是否需要清除数据

        //转换开始时间和结束时间,每次加上一秒钟
        startime = new Date(endtime);
        //结束时间为
        endtime = new Date(+new Date(endtime) + oneminute);
    }
    addData(false);
    checkData(true);//第一次检测数据
    //option数据
    option = {
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: date
    },
    yAxis: {
        boundaryGap: [0, '50%'],
        type: 'value'
    },
    series: [
        {
            name:'数据',
            type:'line',
            markLine : {
                symbol:"none",               //去掉警戒线最后面的箭头
                // label:{
                //     position:"start",          //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                //     normal:{
                //         formatter:'一级\n阈值'
                //     }
                // },
                data : [{
                    silent:false,             //鼠标悬停事件  true没有，false有
                    name:'一级\n阈值',
                    lineStyle:{               //警戒线的样式  ，虚实  颜色
                        type:"solid",
                        color:"#fa9e7f",
                        width:3
                    }, label:{
                        show:true,
                        position:'end',
                        formatter: '一级\n阈值'
                    },
                    yAxis: firstThreshold           // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },{
                    silent:false,
                    name:'二级\n阈值',
                    lineStyle:{               //警戒线的样式  ，虚实  颜色
                        type:"solid",
                        color:"#fa0c3b",
                        width:3
                    },
                    label:{
                        show:true,
                        position:'end',
                        formatter: '二级\n阈值'
                    },
                    yAxis: secondThreshold
                }]
            },
            smooth:true,
            symbol: 'none',
            stack: 'a',
            itemStyle:{
                normal:{
                    lineStyle:{
                        color:'#80cdff'  //线的颜色
                    }
                }
            },
            areaStyle: {
                normal: {
                    color:'#80cdff',
                }
            },
            data: data
        }
    ]
};
//定时启动每一秒刷新一次
setInterval(function () {
    addData(true);
    checkData(false);//检测数据是否超过阈值
    myChart.setOption({
        xAxis: {
            data: date
        },
        series: [{
            name:'数据',
            data: data
        }]
    });
}, 1000);;
function checkData(IsFirst){
    //data超过阈值变为异常，多几个异常则为预警
    //如果是第一次添加
    if (IsFirst == true) {
        var currentDate = "";
        for (var i = 0; i < data.length; i++) {
            if (firstThreshold > 0)//如果data是正数
            {
                if (data[i] > secondThreshold) {//如果达到二级阈值
                    SecondWarningCount++;
                    currentDate = date[i];
                    addWarningData(currentDate,0,1);
                }
                else if (data[i] > firstThreshold) { // 如果达到一级阈值
                    FirstWarningCount++;
                    currentDate = date[i];
                    addWarningData(currentDate,1,0);
                }

            }
            else { //如果data是负数
                if (data[i] < secondThreshold) {//如果达到二级阈值
                    SecondWarningCount++;
                    currentDate = date[i];
                    addWarningData(currentDate,0,1);
                }
                else if (data[i] < firstThreshold) { // 如果达到一级阈值
                    FirstWarningCount++;
                    currentDate = date[i];
                    addWarningData(currentDate,1,0);
                }
            }
        }
    }else{//不是第一次添加
        //console.log(data);
        var Dlength = data.length;
        var currentDate = "";
        if (firstThreshold > 0)//如果data是正数
        {
            if (data[Dlength-1] > secondThreshold) {//如果达到二级阈值
                SecondWarningCount++;
                //先获取数值对应的时间
                currentDate = date[Dlength-1];
                addWarningData(currentDate,0,1);
            }
            else if (data[Dlength-1] > firstThreshold) { // 如果达到一级阈值
                FirstWarningCount++;
                currentDate = date[Dlength-1];
                addWarningData(currentDate,1,0);
            }

        }
        else { //如果data是负数
            if (data[Dlength-1] < secondThreshold) {//如果达到二级阈值
                SecondWarningCount++;
                currentDate = date[Dlength-1];
                addWarningData(currentDate,0,1);
            }
            else if (data[Dlength-1] < firstThreshold) { // 如果达到一级阈值
                FirstWarningCount++;
                currentDate = date[Dlength-1];
                addWarningData(currentDate,1,0);
            }
        }
    }
    //判断是否到达最大异常数
    var updateID;
    if (FirstWarningCount > maxWarning){
    // if (true){
        //一级阈值到达报警数目
        $.ajaxSettings.async = false;//设置ajax同步提交
        $.getJSON("/bridge/getEarlyWarningByPara/"+paraId,function (EarlyWarningresult) {
            updateID = EarlyWarningresult["id"];
        })
        addEarlyWarning(1,0,updateID);
    }
    if(SecondWarningCount > maxWarning){

    }
}
if (option && typeof option === "object") {
    myChart.setOption(option, true);
}
//增加预警信息
    function addEarlyWarning(level,groupid,updateID) {
        //获取当前系统时间
        var bridgeId = $("#bridgeId").text();
        var EarlyWarningDate = new Date();
        var EarlyWarningDateFormat = EarlyWarningDate.getFullYear() + "-" + (EarlyWarningDate.getMonth()+1) + "-" + EarlyWarningDate.getDate() + " " + EarlyWarningDate.getHours()+":"+ EarlyWarningDate.getMinutes() +":"+EarlyWarningDate.getSeconds();
        var GroupID =0;//默认为0，默认从session中去取
        //ajax请求增加数据
        $.ajax(
            {
                url:"/bridge/addEarlyWarning",
                type:"POST",
                dataType:"json",
                async:false,
                data:{ID:updateID,BridgeID:bridgeId,ParaID:paraId,cdName:cdName,Level:level,Type:paraType,GroupID:groupid,IsRemove:0,CreateTime:EarlyWarningDateFormat},
                success:function (result) {
                    console.log(result);
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    console.log(err);
                }
            });
    }
//根据预警信息获取实时数据
    function  getEarlyWarningByParaID(ParaID) {
    //请求接口
        $.ajax(
            {
                url:"/bridge/realtimesensordata",
                type:"POST",
                dataType:"json",
                async:false,
                data:{paraid:paraid,starttime:startime,endtime:endtime},
                success:function (result) {
                    //console.log(result);
                    $.each(result,function (i,item) {
                        //将数据添添加到数组中去
                        date.push(item["collectTime"]);
                        data.push(item["paraValue"]);
                        AllDetailData[item["collectTime"]]=item;//以时间来存储对象
                    });
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    console.log(err);
                }
            });
    }
//添加异常数据
    function addWarningData(WarningTime,ReachFirst,ReachSecond){
        //去查找对应的时间段内部找对应的数据
        var bridgeId = $("#bridgeId").text();
        var WarningData = AllDetailData[WarningTime];
        WarningData["ReachFirst"] = ReachFirst;
        WarningData["ReachSecond"] = ReachSecond;
        //ajax提交数据
        $.ajax(
            {
                url:"/bridge/addWarningData",
                type:"POST",
                dataType:"json",
                async:false,
                data:{BridgeID:bridgeId,ParaTypeCode:WarningData["paraTypeCode"],ParaID:WarningData["paraID"],ParaValue:WarningData["paraValue"],CollectTime:WarningData["collectTime"],SystemTime:WarningData["systemTime"],ReachFirst:WarningData["ReachFirst"],ReachSecond:WarningData["ReachSecond"]},
                success:function (result) {
                    console.log(result);
                    // $.each(result,function (i,item) {
                    //     //将数据添添加到数组中去
                    //     //console.log()
                    // });
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    console.log(err);
                }
            });
    }
}


//异步加载获取异常信息和预警信息
$(function () {
    getWarningData();//第一次获取
    getEarlyWarning();
    setInterval(function () {
        getWarningData();
        getEarlyWarning();
    },2000);//两秒钟获取一次数据
})
//获取异常数据函数
function getWarningData() {
    //获取选取的ID
    var selected_sensor = $('#sensor_group').children('option:selected').val();
    if (selected_sensor == "0") { //如果是获取全部数据
        //获取桥的ID
        var bridgeId = $("#bridgeId").text();
        //获取选中的传感器的值进行传参，进行不同的post
        //使用ajax进行请求
        $.ajax(
            {
                url: "/bridge/allwarningdata",
                type: "POST",
                dataType: "json",
                data: {bridgeid: bridgeId},
                success: function (result) {
                    ReadWarningData(result);
                }
            });
    }else{
        $.ajax(
            {
                url: "/bridge/realtimewarningdata",
                type: "POST",
                dataType: "json",
                data: {paraid: selected_sensor},
                success: function (result) {
                    ReadWarningData(result);
                }
            });
    }
    //console.log(bridgeId);
}
function getEarlyWarning() {
    //获取桥的ID
    var bridgeId = $("#bridgeId").text();

    $.ajax(
        {
            url:"/bridge/allearlywarning",
            type:"POST",
            dataType:"json",
            data:{bridgeid: bridgeId},
            success:function (result) {
                ReadEarlyWarning(result);
            }
        });
}
function ReadWarningData(JsonResult) {
    var warningDataHTml = "";//初始化字符串
    $.each(JsonResult,function (i,item) {
       //遍历读取数据并写入html,拼接html页面
        warningDataHTml += "<tr><td class='text-md-center'>" + item["id"] + "</td><td class='text-md-center'>" + item["paraValue"] + "</td><td class='text-md-center'>" + item["paraTypeCode"] + "</td><td class='text-md-center'>" + item["reachFirst"] + "</td><td class='text-md-center'>" + item["reachSecond"] + "</td><td class='text-md-center'>" + item["systemTime"] + "</td></tr>";
        //console.log(item["paraValue"]);
    });
    //添加字符串
    $("#WarningDataBody").html(warningDataHTml);
}

function ReadEarlyWarning(JsonResult) {
    var earlyWarningHtml = "";
    $.each(JsonResult,function (i,item) {
        //遍历读取数据并写入html,拼接html页面
        earlyWarningHtml += "<tr><td class='text-md-center'>" + item["id"] + "</td><td class='text-md-center'>" + item["type"] + "</td><td class='text-md-center'>" + item["cdName"] + "</td><td class='text-md-center'>" + item["level"] + "</td><td class='text-md-center'>" + item["createTime"] + "</td><td class='text-md-center'><button class='btn-danger' onclick=\"releaseWarning('"+ item["id"] + "')\">解除预警</button></td></tr>";
        //console.log(item["paraValue"]);
    });
    //添加字符串
    $("#EarlyWarningBody").html(earlyWarningHtml);
}